package com.woniu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniu.entity.PageResult;
import com.woniu.entity.Result;
import com.woniu.entity.dto.BrandSearchDTO;
import com.woniu.mapper.BrandMapper;
import com.woniu.pojo.Brand;
import com.woniu.service.IBrandService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author tarnett
 */
@Service
public class BrandServiceImpl implements IBrandService {

    @Resource
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> listSearch(BrandSearchDTO brandSearchDTO) {
        // 1. 开启分页
        PageHelper.startPage(brandSearchDTO.getCurrentPage(), brandSearchDTO.getPageSize());
        // 2. 调用mapper查询数据
        Page<Brand> page = brandMapper.listSearch(brandSearchDTO);
        // 3. 封装分页对象
        PageResult<Brand> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setData(page.getResult());
        // 4. 返回数据
        return pageResult;
    }

    @Override
    public Result save(Brand brand) {
        // 判断名称是否已经存在
        Brand brand1 = checkNameExist(brand.getName());
        if(brand1 != null){
            return Result.error("该名称已经存在");
        }
        return Result.commonByRow(brandMapper.save(brand));
    }

    @Override
    public Integer deleteByIds(Long[] ids) {
        return brandMapper.deleteByIds(ids);
    }

    @Override
    public Result updateById(Brand brand) {
        // 判断名称是否已经存在
        Brand brand1 = checkNameExist(brand.getName());
        if(brand1 != null && !brand1.getId().equals(brand.getId())){
            return Result.error("该名称已经存在");
        }
        return Result.commonByRow(brandMapper.updateById(brand));
    }

    @Override
    public Brand getById(Long id) {
        return brandMapper.getById(id);
    }

    @Override
    public Brand checkNameExist(String name) {
        return brandMapper.checkNameExist(name);
    }

    @Override
    public List<Brand> listAll() {
        return brandMapper.listAll();
    }
}
